package com.colter.project.sample.test.qrcode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

public class ZxingQRCode {

	/** 
     *  
     */
	public ZxingQRCode() {
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ZxingQRCode t = new ZxingQRCode();
		t.encode();
		// t.decode();

	}

	// 编码
	public void encode() {
		try {
			String str = "BEGIN:VCARD"
					+ "\nVERSION:3.0"
					+ "\nN:梁超;"
					+ "\nM:13862093951"
					+ "\nTEL:13862093951"
					+ "\nEMAIL:tianyaxunmeng163@163.com"
					+ "\nIM:QQ:397722599;"
					+ "\nADR:;;江苏省苏州市 原籍：河南省南阳市 ;;;"
					+ "\nIM:格言:只有理想，没有行动，理想永远只是理想！"
					+ "\nORG:只有理想，没有行动，理想永远只是理想！"
					+ "\nTITLE:JavaWeb开发"
					+ "\nURL:http://user.qzone.qq.com/397722599/infocenter#!app=2&via=QZ.HashRefresh&pos=catalog_list"
					+ "\nNOTE:只有理想，没有行动，理想永远只是理想！" + "\nEND:VCARD";

			String path = "E:/test.png";
			BitMatrix byteMatrix;
			String encodeStr = new String(str.getBytes("utf-8"), "iso-8859-1");
			byteMatrix = new MultiFormatWriter().encode(encodeStr,BarcodeFormat.QR_CODE, 240, 240);
			File file = new File(path);

			MatrixToImageWriter.writeToPath(byteMatrix, "png", file.toPath());
			
//			ImageIO.write(MatrixToImageWriter.toBufferedImage(byteMatrix), "jpg", new FileImageOutputStream(file));
			
			System.out.println("-----Generate QR Code success.----------");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 解码
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void decode() {
		try {
			String imgPath = "E:/test.png";
			File file = new File(imgPath);
			BufferedImage image;
			try {
				image = ImageIO.read(file);
				if (image == null) {
					System.out.println("Could not decode image");
				}
				LuminanceSource source = new BufferedImageLuminanceSource(image);
				BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
						source));
				Result result;
				Hashtable hints = new Hashtable();
				hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
				result = new MultiFormatReader().decode(bitmap, hints);
				String resultStr = result.getText();
				System.out.println(resultStr);

			} catch (IOException ioe) {
				System.out.println(ioe.toString());
			} catch (ReaderException re) {
				System.out.println(re.toString());
			}

		} catch (Exception ex) {

		}
	}

}